from flask import Flask,request,jsonify
from flask import Blueprint
from getSql import getSql
from flask_jwt_extended import create_access_token,jwt_required,get_jwt_identity,verify_jwt_in_request
from pymysql.converters import escape_string
import time
import base64
import json
import hashlib
from utils import *

config = Blueprint('config',__name__)

@config.route('/list')
@jwt_required()
def list():
	try:
		all = request.args.get("all")
		user = get_jwt_identity()
		uid = user["id"]
		cursor = getSql()
		if all == '1':
			sql = "select config.*,user.phone,user.realname from config left join user on config.uid = user.id"
		else:
			sql = "select config.*,user.phone,user.realname from config left join user on config.uid = user.id where config.uid = %s" % (uid)
		cursor.execute(sql)
		data = cursor.fetchall()
		return jsonify({"msg": "获取成功","data":data,"code":200})
	except Exception as e:
		return jsonify({"msg": str(e) ,"code":400})

@config.route('/add',methods=["POST"])
@jwt_required()
def add():
	try:
		config = str(request.json.get("config"))
		name = request.json.get("name")
		typea = request.json.get("type")
		createTime = getTime()
		updateTime = createTime
		user = get_jwt_identity()
		uid = user["id"]
		cursor = getSql()
		sql = "INSERT INTO config (uid,config,name,type,createTime,updateTime) VALUES (%s,'%s','%s','%s',%s,%s)" % (uid,escape_string(config),escape_string(name),escape_string(typea),createTime,updateTime)
		cursor.execute(sql)
		return jsonify({"msg": "操作成功","code":200})
	except Exception as e:
		return jsonify({"msg": str(e) ,"code":400})

@config.route('/del',methods=["GET"])
@jwt_required()
def dele():
	try:
		id = request.args.get("id")
		user = get_jwt_identity()
		uid = user["id"]
		cursor = getSql()
		selectSql = "select * from config where id = %s" % (id)
		cursor.execute(selectSql)
		data = cursor.fetchone()
		if data["uid"] !=uid:
			return jsonify({"msg": "删除失败,你没有权限","code":400})
		else:
			sql = "DELETE FROM config where uid = %s and id = %s" % (uid,id)
			cursor.execute(sql)
			return jsonify({"msg": "操作成功","code":200})
	except Exception as e:
		return jsonify({"msg": str(e) ,"code":400})

@config.route('/update',methods=["POST"])
@jwt_required()
def update():
	try:
		name = request.json.get("name")
		typea = request.json.get("type")
		id = request.json.get("id")
		updateTime = getTime()
		user = get_jwt_identity()
		uid = user["id"]
		cursor = getSql()
		selectSql = "select * from config where id = %s" % (id)
		cursor.execute(selectSql)
		data = cursor.fetchone()
		if data["uid"] != uid:
			return jsonify({"msg": "更新失败,你没有权限","code":400})
		sql = "update config set name='%s',type='%s',updateTime = %s where id = %s" % (name,typea,updateTime,id)
		cursor.execute(sql)
		return jsonify({"msg": "操作成功","code":200})
	except Exception as e:
		return jsonify({"msg": str(e) ,"code":400})